package models

import (
	"gorm.io/gorm"
	"net/http"
	"strconv"
	"zk1/common/mysql"
)

type Goods struct {
	gorm.Model
	GoodsDescription string `gorm:"type:varchar(50);not null;comment:商品描述"`
	GoodsCode        int    `gorm:"type:int(15);not null;comment:商品编码"`
	GoodsPrice       int    `gorm:"type:int(10);not null;comment:商品价格"`
	SalesVolume      int    `gorm:"type:int(10);not null;comment:销量"`
	Classification   int    `gorm:"type:tinyint(1);default:1;not null;comment:分类:1 电子产品,2 日常用品,3 衣服"`
	Status           int    `gorm:"type:tinyint(1);default:1;not null;comment:状态:1 出货中,2 已售完,3 已下架"`
}

func (g *Goods) Create() error {
	return mysql.Db.Model(Goods{}).Create(&g).Error
}

func List() (g []*Goods, err error) {
	err = mysql.Db.Model(Goods{}).Find(&g).Error
	return
}

func Paginate(r *http.Request) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		q := r.URL.Query()
		page, _ := strconv.Atoi(q.Get("page"))
		if page <= 0 {
			page = 1
		}

		pageSize, _ := strconv.Atoi(q.Get("page_size"))
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
